<template>
  <el-card>
    <h1>{{ id ? "编辑" : "创建" }}物品</h1>
    <el-form
      :v-model="form"
      label-width="100px"
    >
      <el-form-item label="物品">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="图片">
        <el-upload
          class="avatar-uploader"
          :action="$http.defaults.baseURL + '/upload'"
          :show-file-list="false"
          :on-success="afterUpload"
        >
          <img
            v-if="form.icon"
            :src="form.icon"
            class="avatar"
          >
          <i
            v-else
            class="el-icon-plus avatar-uploader-icon"
          />
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="save()"
        >
          保存
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  props: {
    id: {}
  },
  data() {
    return {
      form: {},
      parents: []
    };
  },
  created() {
    this.id && this.fetch();
    // this.getParent()
  },

  methods: {
      async fetch(){
          const rs = await this.$http.get(`rest/items/${this.id}`)
          this.form= rs.data
      },
    afterUpload(res) {
      console.log(res)
      this.$set(this.form,'icon',res.url)
      // this.form.icon = res.url
      
    },

    async getParent() {
      const rs = await this.$http.get("rest/categories");
      this.parents = rs.data;
    },

    async save() {
      console.log(this.form);
      let rs;
      if (this.id) {
        rs = await this.$http.put(`rest/items/${this.id}`, this.form);
      } else {
        rs = await this.$http.post("rest/items", this.form);
      }
      if (rs.status !== 200) return;
      this.$message({
        message: "成功",
        type: "success"
      });
      this.$router.push({ path: "/items/list" });
    }
  }
};
</script>

<style lang="scss" scoped>
</style>>






